package com.lhy.utilsdemo.aboutFile.controller;

import com.lhy.utilsdemo.aboutFile.service.FileServiceImpl;
import com.lhy.utilsdemo.utils.aboutResult.ResultMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author Liu Hangyu
 * @date 2022/3/10 10:29
 */

@RestController
@RequestMapping("inInDepot")
@Api(tags = {"入库管理"})
@CrossOrigin
public class FileController {

    @Autowired
    private FileServiceImpl fileService;

    //    @UserLoginToken
    @ApiOperation("附件上传")
    @PostMapping("upLoadFile")
    public ResultMap upLoadFile(@RequestParam("file") MultipartFile file) {
        return ResultMap.SUCCESS.setNewData(fileService.upLoadFile(file, "materialFile"));
    }


    @ApiOperation("附件下载")
    @GetMapping("downloadFile")
    public void downloadFile(HttpServletResponse response) {
        // 下载本地文件
        String fileName = "CYL当当发票2.pdf".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = null;// 文件的存放路径
        try {
            inStream = new FileInputStream("\\file\\materialFile\\2022-03-10\\10-41-220300\\CYL当当发票2.pdf");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 设置输出的格式
        response.reset();
//        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ApiOperation("附件预览")
    @GetMapping ("previewFile")
    public void previewFile(HttpServletResponse response,String  path) {
        File file = new File("\\file\\materialFile\\2022-03-10\\10-41-220300\\CYL当当发.pdf");
        if (file.exists()) {
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                System.out.println(e);
            }

        } else {
            return;
        }
    }
}
